package com.le.dub.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.le.dub.common.BusinessRuntimeException;
import com.le.dub.conf.RedisKey;
import com.le.dub.mobile.User;
import com.le.dub.mapper.UserMapper;
import com.le.dub.mobile.bo.UserRegisterBO;
import com.le.dub.service.IAliYunService;
import com.le.dub.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author guole
 * @since 2024-10-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private IAliYunService aliYunService;
    @Resource
    private RedisTemplate template;


    @Override
    public String login(String phone, String password) {


        User user = this.lambdaQuery().eq(User::getPhone, phone).one();
        if (ObjectUtil.isNull(user)) {
            throw new BusinessRuntimeException("500", "账号不存在");

        }
        if(!StrUtil.equals(password,user.getPassword())){
            throw new BusinessRuntimeException("500", "密码错误");

        }
        //设置登录token
        String token = setToken(user.getId());
        return token;
    }

    @Override
    public String register(UserRegisterBO registerBO) {
        //校验验证码
        checkCaptcha(registerBO.getPhone(),registerBO.getCaptcha(),1);
        User user = new User();
        user.setPhone(registerBO.getPhone());
        user.setNick(registerBO.getPhone());
        user.setResidualEnergy(10000);
        user.setPassword(registerBO.getPassword());
        user.setSharingAmount(0);
        user.setWithdrawAmount(0);
        user.setStatus(1);
        user.setCreateTime(new Date());
        this.baseMapper.insert(user);
        //设置登录token
        String token = setToken(user.getId());
        return token;
    }


    @Override
    public void sendCaptcha(String phone, Integer type) {
        String captcha = RandomUtil.randomNumbers(6);

        Boolean b = aliYunService.sendSMS(phone, captcha);
        if (!b) {
            throw new BusinessRuntimeException("500", "验证码短信发送失败");


        }

        if (type == 1) {
            //注册
            //设置验证码有效期为10min
            template.opsForValue().set(RedisKey.registerCaptcha + phone, captcha, 10, TimeUnit.MINUTES);
        } else if (type == 2) {
            //登录
            //设置验证码有效期为10min
            template.opsForValue().set(RedisKey.loginCaptcha + phone, captcha, 10, TimeUnit.MINUTES);
        }

    }

    @Override
    public String setToken(Long userId) {
        String token = UUID.randomUUID().toString().replace("-", "");
        template.opsForValue().set(RedisKey.userToken + token, userId, 1, TimeUnit.DAYS);
        this.lambdaUpdate().eq(User::getId, userId).set(User::getToken, token).update();
        return token;
    }

    @Override
    public void checkUserVoice(Long userId, Integer characterNum) {
        User user = this.getById(userId);
        if (user.getResidualEnergy() < characterNum) {
            throw new BusinessRuntimeException("500", "已使用能量不足，请充值或要求好友");

        }
    }

    @Override
    public void deductUserEnergy(Long userId, Integer characterNum) {
        checkUserVoice(userId, characterNum);
        this.baseMapper.deductUserEnergy(userId, characterNum);
    }

    /**
     * 校验验证码
     *
     * @return
     */
    private void checkCaptcha(String phone, String captcha, Integer type) {
         Object o = null;
        if (type == 1) {
            o = template.opsForValue().get(RedisKey.registerCaptcha + phone);
            template.delete(RedisKey.registerCaptcha + phone);

        } else if (type == 2) {
            o = template.opsForValue().get(RedisKey.loginCaptcha + phone);
            template.delete(RedisKey.loginCaptcha + phone);

        }


        if (ObjectUtil.isNull(o) || !o.toString().equals(captcha)) {
            throw new BusinessRuntimeException("500", "验证码错误，请重新发送验证码");
        }
    }

}
